<template>
  <div class="prod flex ">
    <!-- 导航栏 -->
    <Aside />

    <!-- 主体部分 -->
    <main>
      <!-- 侧边栏 -->
      <Nav ref="isLogin" />
      <div class="center flex">
        <div class="ml-30">
          <History />
        </div>

        <!-- 全部内容 -->
        <div class="content">
          <div class="brand_prodType">
            <!-- 品牌选择 -->
            <div class="brand">
              <div class="searchBox" v-show="brandSearch">
                <input @keyup.enter="searchBrand" v-model="searchVal" class="search" placeholder="Please enter" />
                <el-icon @click="searchBrand" class="searchIcon" size="20">
                  <Search />
                </el-icon>
              </div>
              <el-select @change="changeList" placement="bottom" v-model="treeList" placeholder="Select">
                <el-option v-for="item in treeOptions" :key="item.treeList" :label="item.label" :value="item.treeList" />
              </el-select>
              <div v-infinite-scroll="load" :infinite-scroll-immediate="false" class="btnBox flex fdc">
                <el-button v-for="(item, index) in brandList" :key="index" size="round"
                  :class="{ 'btnActive': className == item.name, 'brandBtn': 'ivy' }" type="text"
                  @click="sendBrandInfo(item.category_id), getBrandProduct(item.brand_id), getId(item)"><span
                    :title="item.name">{{
                      item.name
                    }}</span></el-button>
              </div>
            </div>
            <!-- 型号选择 -->
            <div class="prodType">
              <div class="title">
                <span class="top">MODEL LIST</span>
              </div>
              <div class="btnBox  flex fdc" v-loading="prodListLoading" v-infinite-scroll="brandLoad">
                <el-button v-for="(item, index) in prodList " :key="index" size="round"
                  :class="{ 'brandBtn': true, 'click': clickIndex == item.product_id }" type="text"
                  @click="getInfo(item.product_id, item.model)"><span :title="item.model">{{ item.model
                  }}</span></el-button>
              </div>
            </div>
          </div>

          <!-- 整体数据区域 -->
          <div class="allDataList">
            <!-- 可视化图形表区域 -->
            <div class="figure" ref="figure">
              <!-- echarts图形 -->
              <div class="chart" ref="chart"></div>
            </div>
            <!-- 数据区域 -->
            <div class="dataList">
              <!-- 产品介绍 -->
              <div class="introduce" @click.stop="dialogVisible4 = true">
                <img class="topImg" :src="RenderImg[0]?.image || noPicture()" alt="" />
                <span :title="model" class="topModel">{{ model }}</span>
                <!-- 产品详情弹窗 -->
                <el-dialog @close="closeDialog" :destroy-on-close="true" :close-on-click-modal="false"
                  :close-on-press-escape="false" v-model="dialogVisible4" title="Product details" center>
                  <div class="details_Box">
                    <el-carousel :interval="4000" type="card" height="259px" trigger="click">
                      <el-carousel-item v-for="item in RenderImg" :key="item">
                        <img :src=item.image alt="" @click="PictureEnlargement(item.image)">
                      </el-carousel-item>
                    </el-carousel>
                    <el-dialog :destroy-on-close="true" draggable class="PictureEnlargementBox" v-model="ShowImgs">
                      <img class="PictureEnlargement" :src="Imgs" alt="">
                    </el-dialog>
                    <!-- 弹窗table栏 -->
                    <el-tabs v-model="activeName" class="demo-tabs" @tab-change="handleClick">
                      <!-- 产品信息 -->
                      <el-tab-pane label="Summary" name="first">
                        <div class="summary_box">
                          <h4>Brief Introduction</h4>
                          <div @dblclick="Editfn(event)" class="summary_box_content">
                            <div class="summary_box_item">
                              <p><span>&nbsp;&nbsp;Country Of Origin:</span><span class="describe">Germany</span></p>
                              <p><span>&nbsp;&nbsp;Model:</span>
                                <span data-use="Model" class="describe noEdit">{{ model }}</span>
                              </p>
                              <p><span>&nbsp;&nbsp;Brand:</span><span class="describe noEdit">Original</span></p>
                              <p><span>&nbsp;&nbsp;Cost:</span>
                                <span data-use="Cost" class="describe noEdit">1 Piece</span>
                              </p>
                              <p><span>&nbsp;&nbsp;Product No:</span>
                                <span data-use="ProductNo" class="describe noEdit">110</span>
                              </p>
                              <p><span>&nbsp;&nbsp;Retail price:</span>
                                <span data-use="RetailPrice" class="describe noEdit">$300</span>
                              </p>
                            </div>
                            <div class="summary_box_item">
                              <p><span>&nbsp;&nbsp;Product Name:</span><span class="describe noEdit">Eurodrive inverter
                                  MDX60A0300-503-4-00</span></p>
                              <p><span>&lowast;&nbsp;Length</span>
                                <span data-use="Length" v-show="EditLength" class="describe">{{ Length }}</span>
                                <input v-show="!EditLength" type="text" v-model="EditedLength" />
                                <span @click="closeLength" v-show="!EditLength" class="save">&radic;</span>
                              </p>
                              <p><span>&lowast;&nbsp;Weight:</span>
                                <span data-use="Weight" v-show="EditWeight" class="describe">{{ Weight }}</span>
                                <input v-show="!EditWeight" type="text" v-model="EditedWeight" />
                                <span @click="closeWeight" v-show="!EditWeight" class="save">&radic;</span>
                              </p>
                              <p><span>&lowast;&nbsp;width:</span>
                                <span v-show="EditWide" data-use="Wide" class="describe">{{ Wide }}</span>
                                <input v-show="!EditWide" type="text" v-model="EditedWide" />
                                <span @click="closeWide" v-show="!EditWide" class="save">&radic;</span>
                              </p>
                              <p><span>&lowast;&nbsp;Height:</span>
                                <span data-use="Height" v-show="EditHeight" class="describe">{{ Height }}</span>
                                <input v-show="!EditHeight" type="text" v-model="EditedHeight" />
                                <span @click="closeHeight" v-show="!EditHeight" class="save">&radic;</span>
                              </p>
                            </div>
                          </div>
                          <button class="Save" @click="edit">Save</button>
                          <button class="Delete" @click.stop="dialogVisible4 = false">Close</button>
                        </div>
                      </el-tab-pane>
                      <!-- 产品描述 -->
                      <el-tab-pane label="Description" name="second">
                        <p v-if="descriptionOrEdit" class="Description">{{ productInfo.value?.description }}</p>
                        <!-- 富文本编辑器 -->
                        <div v-else>
                          <div style="border: 1px solid #ccc">
                            <Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef"
                              :defaultConfig="toolbarConfig" :mode="mode" />
                            <Editor @onChange="handleChangeDescript"
                              style="height: 250px; overflow-y: hidden; text-align: left; text-indent: 2rem;"
                              v-model="valueHtml" :defaultConfig="editorConfig" :mode="mode" @onCreated="handleCreated" />
                          </div>
                          <button @click="savePreserve(valueHtml)" class="saves">Preserve</button>
                        </div>
                      </el-tab-pane>
                      <!-- 商品文档 -->
                      <el-tab-pane class="file_box" label="Document" name="third">
                        <ul>
                          <input ref="input" type="file" style="display: none;">
                          <el-button @click="OpenFile" class="addfile" type="primary">Add File</el-button>
                          <el-button :loading="upFileing" class="uploadfile" @click="fileUpload">Upload File</el-button>
                          <el-button :loading="getFiles" class="getfile" @click="getFileList">Refresh</el-button>
                          <li v-for="(item, index) in RenderFiles" :key="index" @click="download(item)">
                            <div class="left">
                              <img class="icon" :src="Icon(item.fileType)" alt="">
                              <p>{{ item.title == null || "" ? 'No title temporarily' : item.title }}</p>
                              <p class="file_text"> {{ item.describe == null || "" ? 'No description' : item.describe }}
                              </p>
                            </div>
                            <div class="right">
                              <span class="time">{{ item?.upload_time }}</span>
                              <span>ID:{{ item?.nickname }}</span>
                            </div>
                          </li>
                        </ul>
                        <el-pagination layout="prev, pager, next" :total="50" v-model:page-size="page_size"
                          v-model:current-page="current_page" @size-change="changeSize" @current-change="changeCurrent" />
                      </el-tab-pane>
                      <!-- 添加文件弹窗 -->
                      <el-dialog :close-on-click-modal="false" :close-on-press-escape="false" class="AddFileDialog"
                        v-model="AddFileDialog" title="Add file description">
                        <div class="FileDialog_box">
                          <p><input class="title" type="text" v-model="FileTitle"
                              placeholder="Please enter the file title"><span class="must">&lowast;</span></p>
                          <el-tree-select v-show="SelectOrInput" check-strictly v-model="FileValue" :accordion="true"
                            :show-checkbox="true" :data="data" :render-after-expand="false" lazy :load="loadNode" multiple
                            @node-click="FileSelect" node-key="id" @check-change="selectCheckbox" />
                          <div class="FileInput_Box" v-show="!SelectOrInput">
                            <el-autocomplete debounce="1000" v-model="ProductName" :fetch-suggestions="querySearchProduct" clearable
                              class="inline-input w-50" placeholder="Please Input" @select="SelectAssociatedProduct" />
                          </div>
                          <el-icon size="25" class="change" @click="SelectOrInput = !SelectOrInput">
                            <Refresh />
                          </el-icon>
                        </div>
                        <!-- 富文本编辑器 -->
                        <div style="border: 1px solid #ccc">
                          <Toolbar style="border-bottom: 1px solid #ccc" :editor="FileEditorRef"
                            :defaultConfig="FileToolbarConfig" :mode="mode" />
                          <Editor @onChange="handleChange" style="height: 300px; overflow-y: hidden;" v-model="FileHtml"
                            :defaultConfig="editorConfig" :mode="mode" @onCreated="FileCreated" />
                        </div>
                        <template #footer>
                          <el-button class="Save" @click="ProducTitleAndDescription" type="primary">Save</el-button>
                          <el-button class="Cance" @click="AddFileDialog = false" type="info">Cancel</el-button>
                        </template>
                      </el-dialog>
                      <!-- 图片上传 -->
                      <el-tab-pane class="upload" label="UploadImg" name="fourth">
                        <el-upload v-model:file-list="fileList" action="''" list-type="picture-card" name="file"
                          :auto-upload="false" :on-change="change" :on-preview="handlePictureCardPreview"
                          :on-remove="handleRemove">
                          <el-icon>
                            <Plus />
                          </el-icon>
                        </el-upload>
                        <button class="Submit" @click="submit">Click Upload</button>
                        <el-dialog v-model="dialogVisibleimg" class="showImg">
                          <img w-full :src="dialogImageUrl" alt="Preview Image" />
                        </el-dialog>
                      </el-tab-pane>
                    </el-tabs>
                  </div>
                </el-dialog>
                <p class="text">
                  <span>{{ description }}</span>
                </p>
              </div>
              <!-- 添加商品 -->
              <button class="New" @click="NewDialog = true">New</button>
              <el-dialog :close-on-click-modal="false" :close-on-press-escape="false" width="750px" class="NewDialog"
                v-model="NewDialog" title="New" draggable>
                <div class="add">
                  <div class="add_content">
                    <div class="left">
                      <p><span><span class="required">&lowast;&nbsp;</span>ProductClass:</span>
                        <button class="choice" @click="dialogVisibleSelectCategory = true">SelectClass</button>
                      </p>
                      <p><i>{{ selectCategory }}</i></p>
                      <p><span><span class="required">&lowast;&nbsp;</span>Model:</span> </p>
                      <p><input placeholder="Please enter" v-model="addmodel" type="text" /></p>
                      <p><span><span class="required">&lowast;&nbsp;</span>Retail price:</span></p>
                      <p><input placeholder="Please enter" v-model="addprice" type="text" /></p>
                      <p><span>&nbsp;Length</span> </p>
                      <p><input placeholder="Please enter" v-model="addlength" type="text" /></p>
                    </div>
                    <div class="right">
                      <p><span>&nbsp;Weight:</span></p>
                      <p><input placeholder="Please enter" v-model="addweight" type="text" /></p>
                      <p><span>&nbsp;Wide:</span></p>
                      <p><input placeholder="Please enter" v-model="addwidth" type="text" /></p>
                      <p><span>&nbsp;Height:</span></p>
                      <p><input placeholder="Please enter" v-model="addheight" type="text" /></p>
                    </div>
                  </div>
                  <button class="footerBtn save" @click="addproduct(categoryid)">Save</button>
                  <button @click="NewDialog = false" class="footerBtn">Cancel</button>
                  <el-dialog v-model="dialogVisibleSelectCategory" title="Select classification" width="30%"
                    :before-close="handleClose">
                    <el-tree :data="data" :props="defaultProps" @node-click="handleNodeClick" />
                  </el-dialog>
                </div>
              </el-dialog>
              <div class="right_box">
                <!-- 产品交易信息 -->
                <div class="deal">
                  <div class="header">
                    <span>Tarde Leads</span>
                    <p class="chooseType">
                      <el-button class="chooseBtn" autofocus @click="openNiche" size="small">Add</el-button>
                    </p>
                    <!-- 添加弹窗 -->
                    <el-dialog :align-center="true" :before-close="closeAdd" :close-on-click-modal="false" class="buy"
                      v-model="dialogVisible" title="Add" width="50%" draggable>
                      <div class="body">
                        <p class="item">
                          <span class="title"><span>*</span>Model</span>
                          <el-input v-model="Model" disabled />
                        </p>
                        <p class="item">
                          <span class="title"><span>*</span>Country</span>
                          <el-autocomplete v-model="country" :fetch-suggestions="querySearch" clearable
                            class="inline-input w-50" placeholder="Please Input" @select="handleSelect" />
                        </p>
                        <p class="item">
                          <span class="title"><span>*</span>Number</span>
                          <el-input v-model="number" placeholder="Please input" clearable />
                        </p>
                        <p class="item">
                          <span class="title"><span>*</span>Cargo_status</span>
                          <el-select placement="bottom" v-model="cargo_statuslist" placeholder="Select">
                            <el-option v-for="item in cargo_statusOptions" :key="item.cargo_statuslist"
                              :label="item.label" :value="item.cargo_statuslist" />
                          </el-select>
                        </p>
                        <p class="item">
                          <span class="title"><span>*</span>Price</span>
                          <el-input v-model="Price" placeholder="Please input" clearable />
                        </p>
                        <p class="item">
                          <span class="title"><span>*</span>Type</span>
                          <el-select placement="bottom" v-model="typelist" placeholder="Select">
                            <el-option v-for="item in typeOptions" :key="item.typelist" :label="item.label"
                              :value="item.typelist" />
                          </el-select>
                        </p>
                        <p class="item">
                          <span class="title"> <span>*</span>Expire</span>
                          <el-date-picker value-format="YYYY-MM-DD" format="YYYY-MM-DD" v-model="expireDate" type="date"
                            placeholder="Pick a day" :size="size" />
                        </p>
                        <p class="item">
                          <span class="title"><span>*</span>Currency</span>
                          <el-select @change=changecy placement="bottom" v-model="currencylist" placeholder="Select">
                            <el-option v-for="item in currencyOptions" :key="item.currencylist" :label="item.label"
                              :value="item.typelist" />
                          </el-select>
                        </p>
                        <p class="item textarea">
                          <span class="title">Remarks</span>
                          <el-input v-model="Remarks" maxlength="255" placeholder="Please input" show-word-limit
                            type="textarea" />
                        </p>
                      </div>
                      <template #footer>
                        <span class="dialog-footer">
                          <el-button class="Cancel" @click="dialogVisible = false">Cancel</el-button>
                          <el-button class="primary" :loading="addTarde" type="primary" @click="nicheAdd">
                            Add
                          </el-button>
                        </span>
                      </template>
                    </el-dialog>
                  </div>
                  <div class="content_00">
                    <p class="title">
                      <span>CNTY</span>
                      <span class="leftOne">QTY</span>
                      <span class="leftTwo">TP</span>
                      <span class="leftThree">TYPE</span>
                      <span class="date">DATE</span>
                    </p>
                    <ul v-infinite-scroll="loadList" :infinite-scroll-immediate="false">
                      <li v-for="(item, index) in TardeLeads" :class="{ activeShow: index % 2 == 0 }" :key="index">
                        <span>{{ item.iso_code_2 }}</span>
                        <span class="leftOne">{{ item.number }}</span>
                        <span class="leftTwo">{{ currency(item) + item.price }}</span>
                        <span class="leftThree">{{ item.type.toUpperCase() }}</span>
                        <span :title="item.create_time" class="date">{{ item.create_time }}</span>
                      </li>
                    </ul>
                  </div>
                </div>
                <!-- 产品货存 -->
                <div class="inventory">
                  <div class="header">
                    <span>In Stock</span>
                    <p class="chooseType">
                      <el-button class="chooseBtn" @click="openStock" autofocus size="small">Add</el-button>
                    </p>
                    <el-dialog :before-close="closeAdd" draggable width="50%" v-model="dialogVisible3" title="New"
                      :close-on-click-modal="false">
                      <div class="body">
                        <p class="item">
                          <span class="title"><span>*</span>Quantity</span>
                          <el-input v-model="stock_quantity" placeholder="Please input" clearable />
                        </p>
                        <p class="item">
                          <span class="title"><span>*</span>Currency</span>
                          <el-select placement="bottom" v-model="currencylist" placeholder="Select">
                            <el-option v-for="item in currencyOptions" :key="item.currencylist" :label="item.label"
                              :value="item.typelist" />
                          </el-select>
                        </p>
                        <p class="item">
                          <span class="title"><span>*</span>Price</span>
                          <el-input v-model="Price" placeholder="Please input" clearable />
                        </p>
                        <p class="item">
                          <span class="title"><span>*</span>Expire</span>
                          <el-date-picker value-format="YYYY-MM-DD" format="YYYY-MM-DD" v-model="expireDate" type="date"
                            placeholder="Pick a day" :size="size" />
                        </p>
                        <p class="item">
                          <span class="title"><span>*</span>Country</span>
                          <el-autocomplete v-model="country" :fetch-suggestions="querySearch" clearable
                            class="inline-input w-50" placeholder="Please Input" @select="handleSelect" />
                        </p>

                        <p class="item">
                          <span class="title"><span>*</span>Condition</span>
                          <el-select placement="bottom" v-model="cargo_statuslist" placeholder="Select">
                            <el-option v-for="item in cargo_statusOptions" :key="item.cargo_statuslist"
                              :label="item.label" :value="item.cargo_statuslist" />
                          </el-select>
                        </p>
                      </div>
                      <template #footer>
                        <span class="dialog-footer">
                          <el-button class="Cancel" @click="dialogVisible3 = false">Cancel</el-button>
                          <el-button class="primary" type="primary" :loading="addStock" @click="stockadd">Add</el-button>
                        </span>
                      </template>
                    </el-dialog>
                  </div>
                  <div class="content_01">
                    <p class="title">
                      <span>CNTY</span>
                      <span class="rightOne">QTY</span>
                      <span class="rightTwo">TP</span>
                      <span class="condition">CONDITION</span>
                    </p>
                    <ul v-infinite-scroll="stockLoad" :infinite-scroll-immediate="false">
                      <li v-for="(item, index) in stockList" :class="{ activeShow: index % 2 == 0 }" :key="index">
                        <span>{{ item?.iso_code_2 }}</span>
                        <span>{{ item?.stock_quantity }}</span>
                        <span>{{ currency(item) }}{{ item?.purchase_price }}</span>
                        <span :title="item.product_condition" class="condition">{{ item?.product_condition }}</span>
                      </li>
                    </ul>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- 聊天区域 -->
          <div class="IM">
            <!-- 右边 -->
            <div class="right">
              <div class="consult flex aic">
                <img src="../../assets/img/候攀.jpg" alt="" />
                <img
                  src="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fc-ssl.dtstatic.com%2Fuploads%2Fblog%2F202103%2F31%2F20210331160001_9a852.thumb.1000_0.jpg&refer=http%3A%2F%2Fc-ssl.dtstatic.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1673675691&t=dcdcdb2297f6a373d82936bf1fb2a5e2"
                  alt="" />
                <img
                  src="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fc-ssl.dtstatic.com%2Fuploads%2Fblog%2F202103%2F31%2F20210331160001_9a852.thumb.1000_0.jpg&refer=http%3A%2F%2Fc-ssl.dtstatic.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1673675691&t=dcdcdb2297f6a373d82936bf1fb2a5e2"
                  alt="" />
              </div>

              <div class="info pl-10 pr-10 f14">
                <div class="flex mt-20">
                  <p class="what ml-10 mt-10">今天天气好好呀</p>
                </div>
                <div class="flex mt-20 jc-e">
                  <p class="what mr-10 mt-10">你在说什么呢</p>
                </div>
                <div class="flex mt-20">
                  <p class="what ml-10 mt-10">我说今天天气好好呀</p>
                </div>
              </div>

              <div class="chat pl-10 pr-10 flex fdc">
                <el-input v-model="chat" :autosize="{ minRows: 5, maxRows: 4 }" type="textarea"
                  placeholder="please enter" />
                <el-button class="mt-10 flex jc-e" type="primary" round>dispatch</el-button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </main>
  </div>
</template>
<script setup>
import Nav from "../components/Nav.vue";
import Aside from "../components/Aside.vue";
// import History from "../components/History.vue";
import Redact from './children/redact.vue';
import { onBeforeMount, onBeforeUnmount, onUpdated, onMounted, ref, reactive, shallowRef } from "vue";
import { useRouter } from 'vue-router';
import * as api from '../../api2/index';
import * as echarts from "echarts";
import "../../../public/tinymce/plugins/media/plugin.min.js";
import "../../../public/tinymce/plugins/preview/plugin.min.js";
import '@wangeditor/editor/dist/css/style.css';
import { Editor, Toolbar } from '@wangeditor/editor-for-vue';
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Refresh, Search } from '@element-plus/icons-vue';
import { forEach } from "lodash";
import { useDemoStore } from '../../pinia/index'
import { i18nChangeLanguage } from '@wangeditor/editor'
//设置编辑器的语言
i18nChangeLanguage('en')
let token = useDemoStore().token
let url = window.localStorage.getItem('url')
// 暂无图片
const noPicture = () => {
  return new URL('../../assets/img/暂无图片.png', import.meta.url).href
}
//型号列表数据
const brandList = ref([])
const prodList = ref([])
// 品牌搜索框
const searchVal = ref('')
const searchBrand = () => {
  brandList.value.splice(0, brandList.value.length)
  getBrand(pageNo.value, pageSize.value, searchVal.value)
}
const prodListLoading = ref(true)

// 品牌下拉菜单
const treeList = ref('CATEGORY')
const treeOptions = [
  {
    treeList: 'BRAND',
    label: 'BRAND'
  },
  {
    treeList: 'CATEGORY',
    label: 'CATEGORY'
  }
]
//品牌搜索框的显示和隐藏
const brandSearch = ref(false)
const pageNo = ref(1)
const pageSize = ref(25)
const changeList = (val) => {
  if (val == 'BRAND') {
    brandList.value.splice(0, brandList.value.length)
    getBrand(pageNo.value, pageSize.value)
    brandSearch.value = true
  } else if (val == 'CATEGORY') {
    pageNo.value = 1
    brandList.value.splice(0, brandList.value.length)
    getProd()
    brandSearch.value = false
  }

}
// 下滑刷新
const load = () => {
  if (treeList.value == 'BRAND') {
    pageNo.value++
    console.log(pageNo.value)
    getBrand(pageNo.value, pageSize.value)
  }
}
// 获取品牌下的产品
const brandPageSize = ref(26)
const brandPageNo = ref(1)
const selectBrandId = ref()
const getBrandProduct = (id) => {
  brandPageNo.value = 1
  selectBrandId.value = id
  if (treeList.value == 'BRAND') {
    myGetBrandProduct(id)
  } else {
    return
  }
}
//品牌下的产品下拉刷新
const brandLoad = () => {
  if (treeList.value == 'BRAND') {
    brandPageNo.value++
    myGetBrandProduct(selectBrandId.value)
  }
}
//获取品牌下的产品接口
const myGetBrandProduct = (id) => {
  api.$getBrandProduct({ token: token, pageNo: brandPageNo.value, pageSize: brandPageSize.value, brand_id: id }).then(res => {
    res.data.data.forEach(item => {
      prodList.value.push(item)
    })
  }).catch(err => {
    console.log(err)
  })
}

// 获取id 动态添加class
const className = ref()
const getId = (id) => {
  className.value = id.name
}
// 获取商品详情
const clickIndex = ref(-1)
const ProductID = ref()
const selectID = ref()
const ProductDetails = ref()
const getInfo = (id, myModel) => {
  clickIndex.value = id
  selectID.value = id
  TardeLeads.value = []
  relationID.value = []
  FileValue.value = []
  stockList.value = []
  RenderFiles.value = []
  BannerImg.value = []
  api.$getInfo({ token: token, productid: id, model: myModel }).then(res => {
    ProductDetails.value = res.data
    model.value = res.data.productInfo.model
    FileValue.value.push(model.value)//默认关联产品
    ProductID.value = res.data.productInfo.product_id//产品id
    ID.value = res.data.productInfo.product_id
    relationID.value.push(res.data.productInfo.product_id)//默认关联产品id
    Model.value = res.data.productInfo.model
    BannerImg.value = res.data.productInfo.image
    description.value = res.data.productInfo.meta_description
    Length.value = res.data.productInfo.length
    Weight.value = res.data.productInfo.weight
    Wide.value = res.data.productInfo.width
    Height.value = res.data.productInfo.height
    myEcharts();
    nicheGetList(ProductID.value, 1)
    stockGetList(stockPageNo.value, ProductID.value)
    HandleImg()
    valueHtml.value = res.data.productInfo.meta_description
  }).catch(err => {
    console.log(err)
  })
}

// 首次默认分类产品
let defaultProduct
// 首次默认产品信息
const productInfo = reactive({})
const description = ref()
// 首次默认轮播图
const BannerImg = ref([])
const RenderImg = ref([])
const HandleImg = () => {
  let url0 = 'http://s7-1500.cn/www/html/product/image/CRM_Product_Image.php?path='
  if (BannerImg.value != null) {
    RenderImg.value = BannerImg.value.map(item => {
      if (item.external == '1') {
        item.image = item.image.replaceAll('\\', '/')
        item.image = url + "/ProductImg/" + item.image
      } else {
        item.image = item.image.replaceAll('.', '&ext=')
        item.image = url0 + item.image
      }
      return item
    })
  } else {
    RenderImg.value = []
  }
  // if(ID.value){
  //   RenderImg.value = BannerImg.value
  // }
  addShowImg()
}
// 轮播图放大
const ShowImgs = ref(false)
const Imgs = ref()
const PictureEnlargement = (img) => {
  ShowImgs.value = true
  Imgs.value = img
}
// 商机列表
const TardeLeads = ref([])
// 获取商机列表
let pageNoList = ref(1)
const nicheGetList = (id, pageNoList) => {
  api.$nicheGetList({ token: token, productid: id, pageNo: pageNoList, pageSize: 10 }).then(res => {
    res.data.forEach(item => {
      TardeLeads.value.push(item)
    })
  }).catch(err => {
    console.log(err)
  })
}
const loadList = () => {
  pageNoList.value = ++pageNoList.value
  nicheGetList(ProductID.value, pageNoList.value)
}
//商机弹窗
const empty = () => {//清空
  number.value = ''
  Price.value = ''
  cargo_statuslist.value = ''
  country.value = ''
  typelist.value = ''
  currencylist.value = ''
  expireDate.value = ''
  Remarks.value = ''
  countryid.value = ''
  stock_quantity.value = ''
}
const addTarde = ref(false)
const Model = ref("");
const number = ref('');
const Price = ref('');
const cargo_statuslist = ref('New Sealed Under Guarantee')
const cargo_statusOptions = [
  {
    cargo_statuslist: 'QB全新保内',
    label: 'New Sealed Under Guarantee'
  },
  {
    cargo_statuslist: 'QG全新过保',
    label: 'New Sealed Beyond Guarantee'
  },
  {
    cargo_statuslist: 'QK全新开封保内',
    label: 'New Unsealed Under Guarantee'
  },
  {
    cargo_statuslist: '"QKG全新开封过保',
    label: '"New Unsealed Beyond Guarantee'
  },
  {
    cargo_statuslist: 'F翻新',
    label: 'Refurbish'
  },
  {
    cargo_statuslist: 'E二手',
    label: 'Used'
  },
  {
    cargo_statuslist: 'J兼容',
    label: 'Substitute'
  },
  {
    cargo_statuslist: 'G高仿无牌',
    label: 'High Copy Blank Brand'
  },
  {
    cargo_statuslist: 'GD高仿带牌',
    label: 'High Copy With Brand'
  },
  {
    cargo_statuslist: 'S升级',
    label: 'Upgrade'
  },
  {
    cargo_statuslist: 'W无货',
    label: 'Discontinued'
  }
]
const country = ref('')
//获取国家
const querySearch = (queryString, cb) => {
  let results = [];
  if (queryString == '') {
    cb(results)
  } else {
    api.$nicheCountryList({ token: token, country: queryString }).then(res => {
      let data = []
      res.data.forEach(item => {
        let obj = {
          country_id: item.country_id,
          value: item.name,
          iso_code_2: item.iso_code_2
        }
        data.push(obj)
      })
      results = data
      cb(results)
    }).catch(err => {
      console.log(err)
    })
  }
}
const countryid = ref()
const handleSelect = (val) => {
  console.log('s')
  countryid.value = val.country_id
}
const typelist = ref('Buy')
const typeOptions = [
  {
    typelist: 'Buy',
    label: 'Buy'
  },
  {
    typelist: 'Sell',
    label: 'Sell'
  }
]
const currencylist = ref("USD")
const currencyOptions = [
  {
    typelist: "USD",
    label: "USD"
  },
  {
    typelist: 'EUR',
    label: 'EUR'
  },
  {
    typelist: 'RMB',
    label: 'RMB'
  },
  {
    typelist: 'GBP',
    label: 'GBP'
  },
  {
    typelist: 'CAD',
    label: 'CAD'
  },
  {
    typelist: 'AUD',
    label: 'AUD'
  },
  {
    typelist: 'HKD',
    label: 'HKD'
  }
]
const changecy = (val) => {
}
const expireDate = ref('')
const Remarks = ref('')
//导航栏
const isLogin = ref()
const openNiche = () => {//打开库存弹窗
  if (token) {
    dialogVisible.value = true
  } else {//没有token就先登录或者注册
    ElMessage({
      type: 'error',
      message: 'Please log in first',
    })
    isLogin.value.dialog = true
  }

}
const openStock = () => {
  if (token) {
    dialogVisible3.value = true
  } else {//没有token就先登录或者注册
    ElMessage({
      type: 'error',
      message: 'Please log in first',
    })
    isLogin.value.dialog = true
  }
}
const nicheAdd = () => {
  if (country.value == '') { ElMessage({ type: 'error', message: 'Please select a country!' }); return }
  if (number.value == '') { ElMessage({ type: 'error', message: 'Please enter the quantity!' }); return }
  if (cargo_statuslist.value == '') { ElMessage({ type: 'error', message: 'Please select the goods status!' }); return }
  if (Price.value == '') { ElMessage({ type: 'error', message: 'Please enter the price!' }); return }
  if (typelist.value == '') { ElMessage({ type: 'error', message: 'Please select type!' }); return }
  if (expireDate.value == '') { ElMessage({ type: 'error', message: 'Please select the validity period!' }); return }
  if (currencylist.value == '') { ElMessage({ type: 'error', message: 'Please select currency!' }); return }
  addTarde.value = true
  api.$nicheAdd({
    token: token, model: Model.value, productid: ProductID.value, number: number.value, price: Price.value,
    currency: currencylist.value, cargo_status: cargo_statuslist.value, expire: expireDate.value,
    remarks: Remarks.value, type: typelist.value, countryid: countryid.value
  }).then(res => {
    addTarde.value = false
    if (res.Status == 0) { ElMessage({ message: 'Successfully added', type: 'success' }) }
    dialogVisible.value = false
    pageNoList.value = 1;
    getInfo(selectID.value)
    empty()
  }).catch(err => {
    console.log(err)
    if (res.Status == 1) { ElMessage({ message: 'Add failed', type: 'error' }) }
  })

}
const closeAdd = (done) => {
  ElMessageBox.confirm(
    'Are you sure you want to close? The information already filled in will be clear?',
    'Warning',
    {
      confirmButtonText: 'OK',
      cancelButtonText: 'Cancel',
      type: 'warning',
    }
  ).then(() => {
    done()
    empty()
    ElMessage({
      type: 'success',
      message: 'Closed'
    })
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: 'Canceled'
    })
  })
}
// 库存弹窗
const addStock = ref(false)
const dialogVisible3 = ref(false)
const stock_quantity = ref('')
const stockadd = () => {
  if (stock_quantity.value == '') { ElMessage({ type: 'error', message: 'Please enter the inventory quantity!' }); return }
  if (currencylist.value == '') { ElMessage({ type: 'error', message: 'Please select currency!' }); return }
  if (Price.value == '') { ElMessage({ type: 'error', message: 'Please enter the price!' }); return }
  if (expireDate.value == '') { ElMessage({ type: 'error', message: 'Please select a date!' }); return }
  if (country.value == '') { ElMessage({ type: 'error', message: 'Please select a country!' }); return }
  if (cargo_statuslist.value == '') { ElMessage({ type: 'error', message: 'Please select the goods status!' }); return }
  addStock.value = true
  api.$stockadd({
    token: token, quantity: stock_quantity.value, currency: currencylist.value,
    expire: expireDate.value, countryid: countryid.value, price: Price.value,
    condition: cargo_statuslist.value, productid: ID.value
  }).then(res => {
    addStock.value = false
    ElMessage({
      type: 'success',
      message: 'Successfully added'
    })
    dialogVisible3.value = false
    stockPageNo.value = 1
    getInfo(selectID.value)
    empty()
  }).catch(err => {
    console.log(err)
  })
}
// 获取库存列表
const stockPageNo = ref(1);
const stockPageSize = ref(10);
const stockList = ref([])
const stockGetList = (pageNo, id) => {
  api.$stockGetList({ token: token, pageNo: pageNo, pageSize: stockPageSize.value, productid: id }).then(res => {
    res.data.forEach(item => {
      stockList.value.push(item)
    })
  }).catch(err => {
    console.log(err)
  })
}
// 下拉加载库存列表
const stockLoad = () => {
  stockPageNo.value = ++stockPageNo.value
  stockGetList(stockPageNo.value, ProductID.value)
}
//获取产品数据
// 首次加载
let categoryTree = []
let model = ref('')
const ID = ref()
const getProd = () => {
  let productid = 52582;
  api.$product({ token: token, productid: productid }).then(res => {
    productInfo.value = res.data.productInfo;
    BannerImg.value = res.data.productInfo.image
    ID.value = productInfo.value.product_id
    description.value = productInfo.value.description
    defaultProduct = res.data.defaultProduct;
    model.value = productInfo.value.model;
    FileValue.value.push(model.value)//默认关联产品
    ProductID.value = res.data.productInfo.product_id//产品id
    relationID.value.push(res.data.productInfo.product_id)//默认关联产品id
    TardeLeads.value = res.data.niche
    Model.value = model.value
    stockList.value = res.data.toStock
    Length.value = res.data.productInfo.length
    Weight.value = res.data.productInfo.weight
    Wide.value = res.data.productInfo.width
    Height.value = res.data.productInfo.height
    valueHtml.value = res.data.productInfo.description
    HandleImg();
    sendBrandInfo(defaultProduct);
    for (let key in res.data.categoryTree) {
      brandList.value.push(res.data.categoryTree[key])
      categoryTree.push(res.data.categoryTree[key])
    }
    datafn()
    getInfo(ID.value, model.value)
  }).catch(err => {
    console.log(err);
  })
}
// 获取品牌数据
const getBrand = (pageNo, pageSize, searchBrand = '') => {
  api.$getBrand({ token: token, pageNo: pageNo, pageSize: pageSize, brand_name: searchBrand }).then(res => {
    for (let key in res.data.data) {
      brandList.value.push(res.data.data[key])
    }
  }).catch(err => {
    console.log(err)
  })
}
// 获取分类下的商品
const sendBrandInfo = (value) => {
  console.log(value)
  prodList.value.splice(0, prodList.value.length)
  if (treeList.value == 'CATEGORY') {
    api.$getCategoryProduct({ token: token, category_id: value }).then(res => {
      for (let i = 0; i < res.data.length; i++) {
        prodList.value.push(res.data[i])
      }
    }).catch(err => {
      console.log(err)
    })
  } else {
    return
  }

}
const handleClick = (val) => {
  if (val == 'third') {
    getFileList(val)
  } else {
  }
}
// New弹窗
const NewDialog = ref(false)
// 商品详情弹窗
let dialogVisible4 = ref(false)
const activeName = ref('first')
// 编辑
const Length = ref()
const Weight = ref()
const Wide = ref()
const Height = ref()
const EditLength = ref(true)
const EditWeight = ref(true)
const EditWide = ref(true)
const EditHeight = ref(true)
const EditedLength = ref()
const EditedWeight = ref()
const EditedWide = ref()
const EditedHeight = ref()
const Editfn = () => {
  EditedLength.value = Length.value
  EditedWeight.value = Weight.value
  EditedWide.value = Wide.value
  EditedHeight.value = Height.value
  let e = window.event
  switch (e.target.dataset.use) {
    case 'Length':
      EditLength.value = false
      break;
    case 'Weight':
      EditWeight.value = false
      break;
    case 'Wide':
      EditWide.value = false
      break;
    case 'Height':
      EditHeight.value = false
      break;
  }
}
const closeLength = () => {
  EditLength.value = true
  Length.value = EditedLength.value
}
const closeWeight = () => {
  EditWeight.value = true
  Weight.value = EditedWeight.value
}
const closeWide = () => {
  EditWide.value = true
  Wide.value = EditedWide.value
}
const closeHeight = () => {
  EditHeight.value = true
  Height.value = EditedHeight.value
}
const edit = () => {
  api.$edit({ token: token, productid: ProductID.value, length: Length.value, weight: Weight.value, width: Wide.value, height: Height.value }).then(res => {
    ElMessage({
      type: 'success',
      message: 'Edit succeeded'
    })
  }).catch(err => {
    console.log(err)
  })
}
// 编辑器实例，必须用 shallowRef
const descriptionOrEdit = ref(false)//根据账号权限开启编辑
const power = () => {
  if (useDemoStore().type == 1 || useDemoStore().type == 3) {
    descriptionOrEdit.value = false
  } else {
    descriptionOrEdit.value = true
  }
}
const editorRef = shallowRef()
// 内容 HTML
const valueHtml = ref()
const toolbarConfig = {}
const editorConfig = { placeholder: 'Please enter a product description' }
const handleCreated = (editor) => {
  editorRef.value = editor // 记录 editor 实例，重要！
}
const handleChangeDescript = (editor) => {
  valueHtml.value = editor.getText();
}
//产品描述编辑
const savePreserve = (txt) => {
  api.$descriptionEdit({ token: token, description: txt, productid: ID.value }).then(res => {
    ElMessage({
      type: 'success',
      message: 'Modified successfully'
    })
    getInfo(selectID.value)
  }).catch(err => {
    console.log(err)
  })
}
// 文件分页
const page_size = ref(5)
const current_page = ref(1)
const changeSize = (val) => {
}
const changeCurrent = (val) => {
  getFileList(val)
}
// 获取产品文件
const RenderFiles = ref([])
const getFiles = ref(false)
const getFileList = (num) => {
  RenderFiles.value = []
  getFiles.value = true
  api.$getFileList({ pageSize: page_size.value, pageNo: num, productid: ID.value, token: token }).then(res => {
    res.data.data.forEach(item => {
      let obj = {
        content: item.content,
        describe: item.describe,
        title: item.title,
        upload_time: item.upload_time,
        nickname: item.nickname,
        product_id: item.product_id,
        files_id: item.files_id,
        fileType: item.file_path.slice(item.file_path.indexOf('.') + 1)
      }
      RenderFiles.value.push(obj)
    })
    if (res.Status == 0) {
      ElMessage({
        message: 'File obtained successfully',
        type: 'success'
      })
      getFiles.value = false
    }
  }).catch(err => {
    console.log(err)
  })
}
// 文件下载
const download = (downFile) => {
  const byteCharacters = atob(downFile.content.fileStream
    .replace(/^data:image\/(png|jpeg|jpg);base64,/, ""))
  const byteNumbers = new Array(byteCharacters.length)
  for (let i = 0; i < byteCharacters.length; i++) {
    byteNumbers[i] = byteCharacters.charCodeAt(i);
  }
  const byteArray = new Uint8Array(byteNumbers);
  const blob = new Blob([byteArray], { type: downFile.content.suffix })
  let a = document.createElement('a');
  a.download = `${downFile.title}.${downFile.content.suffix}`;
  a.href = URL.createObjectURL(blob);
  ElMessageBox.confirm('Are you sure you want to download', 'Warning',
    {
      confirmButtonText: 'OK',
      cancelButtonText: 'Cancel',
      type: 'warning',
    }).then(() => {
      a.click();
      ElMessage({
        type: 'success',
        message: 'Downloading',
      })
    }).catch(() => {
      ElMessage({
        type: 'info',
        message: 'Canceled',
      })
    })
}
const filetxt = ref([])
// ~文件上传
const input = ref()
const copyFile = ref([])
const fileType = ref()
const downFile = ref()
const AddFileDialog = ref(false)
const OpenFile = () => {
  
  input.value.click()
  input.value.addEventListener('change', () => {
    filetxt.value = input.value.files[0]
    copyFile.value.push(input.value.files[0])
    filetxt.value = copyFile.value.filter(item => item != undefined)
    fileType.value = input.value.files[0].name.slice(input.value.files[0].name.indexOf('.') + 1)
    downFile.value = input.value.files[0]
    AddFileDialog.value = true
    input.value.value = ''
    input.value.files[0].value = []
  })
}
// 文件上传的标题
const FileTitle = ref()
// 文件上传的描述
const FileEditorRef = shallowRef()
const FileToolbarConfig = {}
const FileHtml = ref()
const FileCreated = (val) => {
  FileEditorRef.value = val
}
const handleChange = (editor) => {
  FileHtml.value = editor.getText()
}
// 关联产品
const ProductName = ref('')
const SelectOrInput = ref(true)
const FileValue = ref([])
const relationID = ref([])
const loadNode = (node, resolve) => {
  if (node.level == 0) {
    resolve(data)
  } else if (node.level == 1) {
    resolve(node.data.children)
  } else if (node.level == 2) {
    api.$fileSelectProduct({ token: token, category_id: node.data.id }).then(res => {
      let data = []
      res.data.data.forEach(item => {
        let obj = {
          id: item.product_id,
          label: item.model
        }
        data.push(obj)
      })
      resolve(data)
    }).catch(err => {
      console.log(err)
    })
  } else {
    resolve([])
  }

}
const querySearchProduct = (queryString, cb) => {
  let results = []
  if (queryString == '') {
    cb(results)
  } else {
    api.$fileSelectProduct({ token: token, model: queryString }).then(res => {
      res.data.data.forEach(item => {
        let obj = {
          value: item.model,
          id: item.product_id
        }
        results.push(obj)
      })
      cb(results)
    }).catch(err => {
      console.log(err)
    })
  }
}
//上传文件自动补全选择
const SelectAssociatedProduct = (val)=>{
  console.log(val)
  relationID.value.push(val.id)
}

const FileSelect = (data) => {
  if (!Object.hasOwn(data, 'children')) {
    FileValue.value.push(data.label)
    relationID.value.push(data.id)
  }
}
const selectCheckbox = (data, selfIsSelect, childrenIsSelect) => {
  if (Object.hasOwn(data, 'children')) {
    FileValue.value.shift()
    FileValue.value.push(model.value)
  }
  if (!Object.hasOwn(data, 'children')) {
    relationID.value.push(data.id)
  }
}
//添加文件的标题和描述
const fileObj = ref([])
const ProducTitleAndDescription = () => {
  if (FileTitle.value == undefined) { ElMessage({ type: 'error', message: 'Title cannot be empty!' }); return }
  if (FileHtml.value == undefined) { ElMessage({ type: 'error', message: 'Description cannot be empty!' }); return }
  if (relationID.value.indexOf(ID.value) == -1) {
    relationID.value.push(ID.value)
  }
  let obj = {
    title: FileTitle.value,
    content: downFile.value,
    describe: FileHtml.value,
    productid: relationID.value,
    fileType: fileType.value
  }
  let sendObj = {
    title: FileTitle.value,
    describe: FileHtml.value,
    productid: relationID.value,
    fileType: fileType.value
  }
  RenderFiles.value.unshift(obj)
  fileObj.value.push(sendObj)
  AddFileDialog.value = false
  FileTitle.value = undefined
  FileHtml.value = undefined
  relationID.value = []
  FileValue.value = []
}
// 文件上传
const upFileing = ref(false)
const fileUpload = () => {

  if (filetxt.value.length == 0) {
    ElMessage({
      type: 'error',
      message: 'Please select a file'
    })
  } else {
    upFileing.value = true
    api.$fileUpload({ token: token, productid: productInfo.value.product_id, content: fileObj.value, files: filetxt.value }).then(res => {
      if (res.Status == 0) {
        ElMessage({ message: 'Upload succeeded', type: 'success' })
        upFileing.value = false
      }
      filetxt.value.splice(0, filetxt.value.length)
      relationID.value = []
      FileValue.value = []
      fileObj.value = []
      copyFile.value = []
    }).catch(err => {
      upFileing.value = false
      console.log(err)
      ElMessage({ message: res.Message, type: 'error' })
    })
  }
}
//文件扩展名与图标
const Icon = (name) => {
  return new URL(`../../assets/img/${name}.png`, import.meta.url).href
}
// 添加商品
const addmodel = ref('')
const addprice = ref('')
const addweight = ref('')
const addnumber = ref('')
const addlength = ref('')
const addwidth = ref('')
const addheight = ref('')
// 添加商品，选择分类弹窗
const selectCategory = ref('')
const data = []
const categoryid = ref('')
const dialogVisibleSelectCategory = ref(false)
const handleNodeClick = (data) => {
  selectCategory.value = data.label
  dialogVisibleSelectCategory.value = false
  categoryid.value = data.id
}
const datafn = () => {
  categoryTree.forEach(item => {
    let obj = {
      label: item.name,
      id: item.category_id,
      children: []
    }
    for (let key in item.child) {
      let obj1 = {
        label: item.child[key].name,
        id: item.child[key].category_id,
        children: []
      }
      obj.children.push(obj1)
    }
    data.push(obj)
  })
}
const defaultProps = {
  children: 'children',
  name: 'name',
}
const addproduct = (id) => {
  let reg = /^(([^0][0-9]+|0)\.([0-9]{1,2})$)|^([^0][0-9]+|0)$/;
  if (addmodel.value == "") { ElMessage({ message: 'Please enter the model', type: 'error' }); return }
  if (addprice.value == '') { ElMessage({ message: 'Please enter the price', type: 'error' }); return }
  if (!reg.test(addprice.value)) { ElMessage({ message: 'Price must be a number', type: 'error' }); return }
  api.$addproduct({ model: addmodel.value, price: addprice.value, weight: addweight.value, token: token, categoryid: id }).then(res => {
    if (res.Status == 0) {
      ElMessage({
        message: 'Successfully added!',
        type: 'success'
      })
      NewDialog.value = false
    } else {
      ElMessage({
        message: 'Add failed',
        type: 'error'
      })
    }
  }).catch(err => {
    console.log(err)
  })
  addmodel.value = ''
  addprice.value = ''
}

// 上传图片
const fileList = ref([])
const addShowImg = () => {
  fileList.value = []
  RenderImg.value.forEach(item => {
    let ShowImg = {
      url: item.image,
      id: item.product_image_id
    }
    fileList.value.push(ShowImg)
  })

}
const dialogImageUrl = ref('')
const dialogVisibleimg = ref(false)
const imgId = []
const handleRemove = (uploadFile, uploadFiles) => {
  console.log(uploadFile)
  imgId.push(uploadFile.id)
  delImg()
}
// 删除图片
const delImg = () => {
  api.$delIamge({ token: token, productid: productInfo.value.product_id, imageid: imgId }).then(res => {
    console.log("删除成功")
    if (selectID.value) {
      getInfo(selectID.value)
    } else {
      getProd();
    }
  }).catch(err => {
    console.log(err)
  })
}
const handlePictureCardPreview = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url
  dialogVisibleimg.value = true
}
const files = ref([])
const change = (uploadFile, uploadFiles) => {
  console.log(uploadFile.raw)
  files.value.push(uploadFile.raw)
}
const submit = () => {
  api.$ImageUpload({ token: token, files: files.value, productid: ID.value }).then(res => {
    ElMessage({
      message: 'Upload succeeded!',
      type: 'success'
    })
    if (selectID.value) {
      getInfo(selectID.value)
    } else {
      getProd();
    }
    files.value = []
  }).catch(err => {
    console.log(err)
    ElMessage({
      message: 'Upload failed!',
      type: 'error'
    })
  })
}
// 关闭详情弹窗
const closeDialog = () => {
}

//货币单位 
const currency = item => {
  switch (item.currency) {
    case 'RMB':
      return '￥'
    case 'USD':
      return '$'
    case 'EUR':
      return '€'
    case 'GBP':
      return '￡'
    case 'CAD':
      return 'C$'
    case 'AUD':
      return 'A$'
    case 'HKD':
      return 'HK$'
  }
}
const chart = ref();
//商机添加弹窗
let dialogVisible = ref(false)

onMounted(() => {
  // getTarde()
  myEcharts();
  textBox();
  getProd();
  power()
});
onUpdated(() => {
  if (prodList.value.length == 0) {
    prodListLoading.value = true
  } else {
    prodListLoading.value = false
  }
  if(useDemoStore().state){
    let canvas = document.querySelector('.chart').children[0].children[0]
    if(canvas){
      canvas.style.width = "1040px"
    }
  }
})
//组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})
onBeforeMount(() => {
  const editor = FileEditorRef.value
  if (editor == null) return
  editor.destroy()
})

// echarts图表
const figure = ref()//图表外面的盒子
const myEcharts = () => {
  let myChart = echarts.init(chart.value);
  let option;
  // 
  function splitData(rawData) {
    let categoryData = [];
    let values = [];
    let volumns = [];
    for (let i = 0; i < rawData.length; i++) {
      categoryData.push(rawData[i].splice(0, 1)[0]);
      values.push(rawData[i]);
      volumns.push([i, rawData[i][1], rawData[i][0] > rawData[i][1] ? 1 : -1]);
    }
    return {
      categoryData: categoryData,
      values: values,
      volumns: volumns
    };
  }
  function calculateMA(dayCount, data) {
    let result = [];
    for (let i = 0, len = data.values.length; i < len; i++) {
      if (i < dayCount) {
        result.push('-');
        continue;
      }
      let sum = 0;
      for (let j = 0; j < dayCount; j++) {
        sum += data.values[i - j][0];
      }
      result.push(+(sum / dayCount).toFixed(3));
    }
    return result;
  }
  api.$product({ token: token, productid: 52582 }).then(res => {
    let rawData = ProductDetails.value?.k || res.data.k
    let data = splitData(rawData);
    myChart.setOption(
      (option = {
        backgroundColor: '#242c37',
        animation: false,
        legend: {
          bottom: 10,
          left: 'center',
          data: ['成交量', '报价']
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
          },
          backgroundColor: 'rgba(255, 255, 255, 0.8)',
          position: function (pos, params, el, elRect, size) {
            let obj = { top: 10 };
            obj[['left', 'right'][+(pos[0] < size.viewSize[0] / 2)]] = 30;
            return obj;
          },
          extraCssText: 'width: 170px'
        },
        axisPointer: {
          link: { xAxisIndex: 'all' },
          label: {
            backgroundColor: '#777'
          }
        },
        toolbox: {
          feature: {
            dataZoom: {
              yAxisIndex: false
            },
            brush: {
              type: ['lineX', 'clear']
            }
          }
        },
        brush: {
          xAxisIndex: 'all',
          brushLink: 'all',
          outOfBrush: {
            colorAlpha: 0.1
          }
        },
        grid: [
          {
            left: '10%',
            right: '8%',
            height: '50%'
          },
          {
            left: '10%',
            right: '8%',
            bottom: '15%',
            height: '15%'
          }
        ],
        xAxis: [
          {
            type: 'category',
            data: data.categoryData,
            scale: true,
            boundaryGap: false,
            axisLine: { onZero: false },
            splitLine: { show: false },
            splitNumber: 20,
            min: 'dataMin',
            max: 'dataMax',
            axisPointer: {
              z: 100
            }
          },
          {
            type: 'category',
            gridIndex: 1,
            data: data.categoryData,
            scale: true,
            boundaryGap: false,
            axisLine: { onZero: false },
            axisTick: { show: false },
            splitLine: { show: false },
            axisLabel: { show: false },
            splitNumber: 20,
            min: 'dataMin',
            max: 'dataMax',
            axisPointer: {
              label: {
                formatter: function (params) {
                  var seriesValue = (params.seriesData[0] || {}).value;
                  return (
                    params.value +
                    (seriesValue != null
                      ? '\n' + echarts.format.addCommas(seriesValue)
                      : '')
                  );
                }
              }
            }
          }
        ],
        yAxis: [
          {
            type: "value",
            scale: true,
            splitArea: {
              show: true
            }
          },
          {
            scale: true,
            gridIndex: 1,
            splitNumber: 2,
            axisLabel: { show: false },
            axisLine: { show: false },
            axisTick: { show: false },
            splitLine: { show: false }
          }
        ],
        dataZoom: [
          {
            type: 'inside',
            xAxisIndex: [0, 1],
            start: 20,
            end: 100
          },
        ],
        series: [
          // {
          //   name: '成交量',
          //   type: 'candlestick',
          //   data: data.values,
          //   itemStyle: {
          //     normal: {
          //       color: '#06B800',
          //       color0: '#FA0000',
          //       borderColor: '#91cc75',
          //       borderColor0: '#58aafc',
          //     }
          //   },
          //   // tooltip: {
          //   //   formatter: function (param) {
          //   //     param = param[0];
          //   //     return [
          //   //       'Date: ' + param.name + '<hr size=1 style="margin: 3px 0">',
          //   //       'Open: ' + param.data[0] + '<br/>',
          //   //       'Close: ' + param.data[1] + '<br/>',
          //   //       'Lowest: ' + param.data[2] + '<br/>',
          //   //       'Highest: ' + param.data[3] + '<br/>'
          //   //     ].join('');
          //   //   }
          //   // }
          // },
          {
            name: '报价',
            type: 'line',
            color: '#f35757',
            data: calculateMA(1, data),
            smooth: false,
            lineStyle: {
              normal: { opacity: 0.5, color: "#d90013", cap: 'square' },
            }
          },
          {
            name: '成交量',
            type: 'bar',
            color: '#32c084',
            xAxisIndex: 1,
            yAxisIndex: 1,
            data: data.volumns
          }
        ]
      }),
      true
    );
  })
  option && myChart.setOption(option);

  //图标大小自适应
  useDemoStore().$subscribe((mutation, state) => {
    console.log(mutation, state.state)
    if (state.state) {
      myChart.resize({
        width: 1040
      })
    } else {
      myChart.resize({
        width: 907
      })
    }
  })
};
const textBox = () => {
  tinymce.init({
    selector: "#mytextarea",
    branding: false,
    language: "zh-Hans",
    a11y_advanced_options: true,
    plugins: "image code link media preview",
    toolbar:
      "undo redo | styleselect | bold | italic | link | image | media | preview ",
    skin_url: "../../../public/tinymce/skins/ui/oxide",
    promotion: false,
    height: "320px",
    //   'alignleft aligncenter alignright',
    /* enable title field in the Image dialog*/
    image_title: true,
    /* enable automatic uploads of images represented by blob or data URIs*/
    automatic_uploads: true,
    /*
      URL of our upload handler (for more details check: https://www.tiny.cloud/docs/configure/file-image-upload/#images_upload_url)
      images_upload_url: 'postAcceptor.php',
      here we add custom filepicker only to Image dialog
    */
    file_picker_types: "image file media",
    /* and here's our custom image picker*/
    file_picker_callback: (cb, value, meta) => {
      const input = document.createElement("input");
      input.setAttribute("type", "file");
      input.setAttribute("accept", "image/*");

      input.addEventListener("change", (e) => {
        const file = e.target.files[0];

        const reader = new FileReader();
        reader.addEventListener("load", () => {
          /*
            Note: Now we need to register the blob in TinyMCEs image blob
            registry. In the next release this part hopefully won't be
            necessary, as we are looking to handle it internally.
          */
          const id = "blobid" + new Date().getTime();
          const blobCache = tinymce.activeEditor.editorUpload.blobCache;
          const base64 = reader.result.split(",")[1];
          const blobInfo = blobCache.create(id, file, base64);
          blobCache.add(blobInfo);

          /* call the callback and populate the Title field with the file name */
          cb(blobInfo.blobUri(), { title: file.name });
        });
        reader.readAsDataURL(file);
      });

      input.click();
    },
    content_style:
      "body { font-family:Helvetica,Arial,sans-serif; font-size:16px }",
  });
};
</script>
<style lang="less" scoped>
@import "./css/product.less";
</style>